package team.seekers.oj.group.controller;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import team.seekers.oj.common.annotation.UserSession;
import team.seekers.oj.common.entity.ApiResponseBody;
import team.seekers.oj.common.entity.PageResult;
import team.seekers.oj.common.entity.UserSessionDTO;
import team.seekers.oj.common.enums.ApiExceptionEnum;
import team.seekers.oj.common.util.AssertUtils;
import team.seekers.oj.group.dto.GroupCreateReqDTO;
import team.seekers.oj.group.dto.GroupListDTO;
import team.seekers.oj.group.dto.GroupListReqDTO;
import team.seekers.oj.group.dto.GroupManageDTO;
import team.seekers.oj.group.entity.vo.GroupInfoVO;
import team.seekers.oj.group.service.GroupExtensionService;
import team.seekers.oj.group.service.GroupService;

import javax.validation.Valid;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
@Controller
@RequestMapping("/manage/group")
public class GroupManageController {

    @Autowired
    private GroupService groupService;

    @Autowired
    private GroupExtensionService groupExtensionService;

    @PostMapping("/create")
    @ApiResponseBody
    public Long create(@RequestBody @Valid GroupCreateReqDTO reqDTO,
                       @UserSession UserSessionDTO userSessionDTO) {
        // 增补
        reqDTO.setUserId(userSessionDTO.getUserId());

        List<Long> userIds = Optional.ofNullable(reqDTO.getUsers()).orElse(Lists.newArrayList());
        reqDTO.setUsers(userIds.stream().distinct().collect(Collectors.toList()));

        return groupService.create(reqDTO);
    }

    @GetMapping("/page")
    @ApiResponseBody
    public PageResult<GroupListDTO> page(@RequestBody @Valid GroupListReqDTO reqDTO) {
        return groupService.page(reqDTO);
    }

    @GetMapping("/query")
    @ApiResponseBody
    public GroupInfoVO query(@RequestParam("groupId") long groupId,
                             @UserSession UserSessionDTO userSessionDTO) {
        GroupInfoVO groupInfoVO = groupService.getVO(groupId);
        return groupInfoVO;
    }


    @GetMapping("/join")
    @ApiResponseBody
    public Void join(@RequestParam("groupId") long groupId,
                                @UserSession UserSessionDTO userSessionDTO) {
        groupService.addUser(groupId,userSessionDTO.getUserId());
        return null;
    }

    @GetMapping("/out")
    @ApiResponseBody
    public Void out(@RequestParam("groupId") long groupId,
                     @UserSession UserSessionDTO userSessionDTO) {
        groupService.removeUser(groupId,userSessionDTO.getUserId());
        return null;
    }
}